#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import requests
import json
import sys
import time
import datetime
import re
import sqlite3
from bottle import route, run, template, static_file
import bottle


curpath = os.path.dirname(__file__)
bottle.TEMPLATE_PATH.insert(0, os.path.join(curpath, "views"))
bottle.TEMPLATE_PATH.insert(0, os.path.join(curpath, "html"))
bottle.TEMPLATE_PATH.insert(0, "/dev/shm/")

# ('N','T','Q','Qs','Q1')
# (1, '1', '1.行政机关依法作出不予行政许可书面决定的，应说明理由并告知申请人享有依法申请行政复议的权利。 （   ）', '√', '1.√', '对')
# ('N','T','A','B','C','D','Q','Qs')
# (1, '1', '1.职业的特征不包括（   ）。', 'A.目的性', 'B.稳定性', 'C.规范性', 'D.无忧性', 'D', '1.D')


@route("/html/<filepath:path>")
def server_static(filepath):
    return static_file(filepath, root="/dev/shm/")


@route("/")
@route("/<page>")
def get_tms(page=1):
    pagesize = 5
    pageindex = (int(page) - 1) * pagesize
    jsfile = os.path.join("/dev/shm", f"{page}.js")
    if os.path.exists(jsfile):
        return template("index", fn=f"{page}.js")
    conn = sqlite3.connect("m.db")
    cur = conn.cursor()
    cur.execute(f"select * from xzt limit {pagesize} offset {pageindex}")
    rows = cur.fetchall()
    # conn.commit()
    # cur.close()
    # conn.close()
    tms = []

    for row in rows:
        tm = {"type": "single", "value": 5, "question": "", "answers": []}
        tm["question"] = row[2]
        for i, j in enumerate(["A", "B", "C", "D"]):
            xx = {}
            xx["answer"] = row[i + 3]
            xx["right"] = True if row[7] == j else False
            tm["answers"].append(xx)
        tms.append(tm)
    tms = json.dumps(tms, ensure_ascii=False)
    with open(jsfile, "w") as f:
        f.write("let questions =" + str(tms))
    return template("index", fn=f"{page}.js")


run(host="0.0.0.0", port=8080, debug=True)

# {
# question: "鸡是胎生动物？",
# type: "judge",
# value: 5,
# answers: false,
# }
